package com.tbsoft.ehr.login.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.tbsoft.ehr.login.LoginInfo;
import com.tbsoft.ehr.login.UserInfo;
import com.tbsoft.ehr.login.service.LoginService;

/**
 * @desc 安全验证 filter
 * @author vastdream
 * 
 */
public class EhrSecurityFilter implements Filter {
	private Log log = LogFactory.getLog(getClass());

	@Override
	public void destroy() {

	}

	private String loginUrl;

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public String getLoginSubmit() {
		return loginSubmit;
	}

	public void setLoginSubmit(String loginSubmit) {
		this.loginSubmit = loginSubmit;
	}

	private String loginSubmit;

	private String defaultForwardUrl;

	public String getDefaultForwardUrl() {
		return defaultForwardUrl;
	}

	public void setDefaultForwardUrl(String defaultForwardUrl) {
		this.defaultForwardUrl = defaultForwardUrl;
	}
	
	private String logoutUrl;
	
	public synchronized String getLogoutUrl() {
		return logoutUrl;
	}

	public synchronized void setLogoutUrl(String logoutUrl) {
		this.logoutUrl = logoutUrl;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
			ServletException {
		log.debug("EhrSecurityFilter start.....");
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String url = httpRequest.getRequestURI();
		String rootUrl = httpRequest.getContextPath() + "/";
		log.debug("url:" + url + ",rootUrl:" + rootUrl);

		HttpSession httpSession = httpRequest.getSession();
		log.debug("session.id" + httpSession.getId());
		LoginInfo loginInfo = (LoginInfo) httpSession.getAttribute("loginInfo");
		if (loginInfo == null) {
			loginInfo = new LoginInfo();
			httpSession.setAttribute("loginInfo", loginInfo);
		}

		// 登录页面不做拦截
		if (url.equals(rootUrl + loginUrl)) {
			filterChain.doFilter(httpRequest, response);
			return;
		}
		//退出页面
		if(url.equals(rootUrl + logoutUrl)){
			httpSession.removeAttribute("loginInfo");
			httpResponse.sendRedirect(rootUrl + loginUrl);
			return;
		}
		// 过滤页面不做拦截
		for (String excludeUrl : excludeUrlList) {
			if (url.matches(rootUrl + excludeUrl)) {
				filterChain.doFilter(httpRequest, response);
				return;
			}
		}
		// 验证用户数据
		if (url.equals(rootUrl + loginSubmit)) {
			String randCode = (String) httpSession.getAttribute("randCode");
			String j_veriCode = httpRequest.getParameter("j_veriCode");
			if(!randCode.equalsIgnoreCase(j_veriCode)){
				httpRequest.setAttribute("j_username", httpRequest.getParameter("j_username"));
				httpRequest.setAttribute("j_password", httpRequest.getParameter("j_password"));
				httpRequest.setAttribute("errorInfo", "验证码不正确");
				httpRequest.getRequestDispatcher(loginUrl).forward(httpRequest, httpResponse);
				return;
			}
			if (!loginService.AutherUserInfo(httpRequest)) {
				httpRequest.setAttribute("j_username", httpRequest.getParameter("j_username"));
				httpRequest.setAttribute("errorInfo", "用户名/密码不正确");
				httpRequest.getRequestDispatcher(loginUrl).forward(httpRequest, httpResponse);
				return;
			} else {
				loginInfo = (LoginInfo) httpSession.getAttribute("loginInfo");
				httpSession.invalidate();
				httpRequest.getSession(true).setAttribute("loginInfo", loginInfo);
				String forwardUrl = loginInfo.getForwardUrl() != null ? loginInfo.getForwardUrl() : rootUrl
						+ defaultForwardUrl;
					httpResponse.sendRedirect( rootUrl+ defaultForwardUrl);
				return;
			}
			 
		}
		// 检查用户数据是否存在

		// 不存在
		if (loginInfo.getUserId() == null || loginInfo.getUserId().isEmpty()) {
			// 记录url
			loginInfo.setForwardUrl(url);
			// 根路径则跳转到登录面
			if(url.endsWith(".do")){
				httpResponse.getWriter().append("{statusCode : 301}");
			}else{
				httpResponse.sendRedirect(rootUrl + loginUrl);
			}
			
			return;
		} else {
			if (url.equals(rootUrl) || url.endsWith(rootUrl + defaultForwardUrl)) { // 如果是到主页则要查询角色和菜单权限
				UserInfo ui = loginService.getUserInfoById(loginInfo.getUserId());
				if(ui != null){
					loginInfo.setRoleSet(ui.getRoleSet());
				}
				httpRequest.setAttribute("userInfo", ui);
			}
			filterChain.doFilter(httpRequest, response);
		}

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

	private List<String> excludeUrlList;

	public List<String> getExcludeUrlList() {
		return excludeUrlList;
	}

	public void setExcludeUrlList(List<String> excludeUrlList) {
		this.excludeUrlList = excludeUrlList;
	}

	private LoginService loginService;

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

}
